<template>
  <el-dialog title="配镜发料详情" :close-on-click-modal="false" :visible.sync="visible" center fullscreen>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" inline  ref="dataForm"  label-width="80px">
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="加工中心" prop="workDeptId">
            <el-select v-model="dataForm.workDeptId" placeholder="请选择" @change="outDeptChange($event)">
              <el-option v-for="item in deptOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售门店" >
            <el-input v-model="dataForm.deptName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配镜时间" >
            <el-input v-model="dataForm.createTime" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="取镜门店" >
            <el-input v-model="dataForm.takeMirroDeptName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="取镜时间" >
            <el-input v-model="dataForm.takeMirroTime" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配镜单号" >
            <el-input v-model="dataForm.billId" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="顾客名称" >
            <el-input v-model="dataForm.customerName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="顾客电话" prop="customerPhone">
            <el-input v-model="dataForm.customerPhone" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <table class="miui-table">
      <tr>
        <th>右眼(OD)/左眼(OS)</th>
        <th>BC</th>
        <th>球镜</th>
        <th>柱镜</th>
        <th>轴向</th>
        <th>曲率1</th>
        <th>曲率2</th>
        <th>直径</th>
        <th>VA</th>
        <th>适用镜片</th>
        <th>片/盒数</th>
        <th>三棱镜</th>
        <th>基底</th>
        <th>远用瞳距(mm)</th>
        <th>瞳高(mm)</th>
        <th>远用VA</th>
        <th>镜片种类</th>
      </tr>
      <tr>
        <td>OD</td>
        <td>{{optometryDetail.bcOd}}</td>
        <td>{{optometryDetail.ballGlassOd}}</td>
        <td>{{optometryDetail.postGlassOd}}</td>
        <td>{{optometryDetail.axesOd}}</td>
        <td>{{optometryDetail.curvatureOd1}}</td>
        <td>{{optometryDetail.curvatureOd2}}</td>
        <td>{{optometryDetail.diameterOd}}</td>
        <td>{{optometryDetail.invisibleOd}}</td>
        <td>{{optometryDetail.suitableGlassOd}}</td>
        <td>{{optometryDetail.numberBoxOd}}</td>

        <td>{{optometryDetail.arriseGlassOd}}</td>
        <td>{{getBasalTypeData(optometryDetail.basisOs)}}</td>
        <td>{{optometryDetail.farPupilDistanceOd}}</td>
        <td>{{optometryDetail.pupilHighOd}}</td>
        <td>{{optometryDetail.farUseOd}}</td>
        <td>{{valueOrNameTypeChange(dataForm.saleType)}}</td>
      </tr>
      <tr>
        <td>OS</td>
        <td>{{optometryDetail.bcOs}}</td>
        <td>{{optometryDetail.ballGlassOs}}</td>
        <td>{{optometryDetail.postGlassOs}}</td>
        <td>{{optometryDetail.axesOs}}</td>
        <td>{{optometryDetail.curvatureOs1}}</td>
        <td>{{optometryDetail.curvatureOs2}}</td>
        <td>{{optometryDetail.diameterOs}}</td>
        <td>{{optometryDetail.invisibleOs}}</td>
        <td>{{optometryDetail.suitableGlassOs}}</td>
        <td>{{optometryDetail.numberBoxOs}}</td>
        <td>{{optometryDetail.arriseGlassOs}}</td>
        <td>{{getBasalTypeData(optometryDetail.basisOs)}}</td>
        <td>{{optometryDetail.farPupilDistanceOs}}</td>
        <td>{{optometryDetail.pupilHighOs}}</td>
        <td>{{optometryDetail.farUseOs}}</td>
        <td>{{valueOrNameTypeChange(dataForm.saleType)}}</td>
      </tr>
    </table>
    <el-table :data="dataList" border v-loading="dataListLoading" :row-class-name="tableRowClassName" style="margin-top: 20px;">
      <el-table-column width="60">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-refresh" circle v-if="[3,5].includes(scope.row.ctgSaleId) && !scope.row.newGoods" @click="goodsChangeHandle(scope.row)"></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="goodsCode" label="商品代码" width="170"></el-table-column>
      <el-table-column prop="goodsDisplayName" label="商品名称"></el-table-column>
      <el-table-column prop="goodsQuantity" label="商品数量" width="80"></el-table-column>

        <!--     镜片类型(L-左镜片,R-右镜片,F-镜架)-->
      <el-table-column prop="glassFlag" label="右眼(R)/左眼(L)" width="120"></el-table-column>
      <el-table-column prop="spec" label="出库仓位" width="170">
        <template slot-scope="scope">
          <el-select v-model="scope.row.outStockId" :disabled="scope.row.outStorageFlag == 1 || userInfo.deptType != 3">
            <el-option v-for="item in stockOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
      <el-button @click="visible = false">关闭</el-button>
    </span>
    <search-goods v-if="goodsVisible" ref="goodsDialog" @refreshForm="getNewGood"></search-goods>
  </el-dialog>
</template>

<script>
    import { getGlassesVOById,updateSendGlassSale} from '@/api/eims/optician/glassSend.js'
    import {getStockList} from '@/api/eims/stock.js'
    import {saveNewCheckOrder,saveAndAuditOrder,getStockDataList,getCtgDataList} from '@/api/eims/check'
    import {allocationApplyAdd,allocationApplyGetObj,allocationApplyEdit} from '@/api/eims/allocation-apply'
    import {fetchTree,getDeptInfoByDeptTypes} from '@/api/admin/dept.js'
    import { mapGetters } from 'vuex'

    import SearchGoods from '../components/SearchGoods'

    export default {
    data () {
      return {
				ischeck: false,
        visible: false,
        dataForm: {
          id: 0,
          billId:'',
          workDeptId:'',
          outDeptId: '',
          outDeptName: '',
          inDeptId: '',
          inDeptName: '',
          memo: '',
          detailList: []
        },
        deptOptions: [],
        stockOptions: [],
        dataList: [],
        optometryDetail: {},
        dataListLoading: false,
        dataRule: {workDeptId: [{ required: true,message: '请选择加工部门',trigger: 'blur'}]},
        selectionList: [],
        receiveListVisible: false,
        goodsVisible: false,
        typeOptions: [
            {value: '1', name: '隐形订做'},
            {value: '2', name: '框镜订做'},
            {value: '3', name: '隐形成品'},
            {value: '4', name: '框镜成品'},
            {value: '5', name: '辅料'}
        ]
      }
    },
    components: {
      SearchGoods
    },
    computed: {
        ...mapGetters(['bizData','userInfo'])
    },
    methods: {
      init (id) {
        this.getDeptList()
        this.getOutStockList()
        this.dataForm.id = id || 0
        this.visible = true
        this.dataList = []
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
              getGlassesVOById(this.dataForm.id).then(result=>{
                  this.dataForm = result.data.data
                  let goodsData = result.data.data.detailList
                  this.optometryDetail = result.data.data.optometry
                  this.dataList = JSON.parse(JSON.stringify(goodsData))
                  this.submitList = JSON.parse(JSON.stringify(goodsData))
              })
          }
        })
      },
      outDeptChange($event) {
        this.deptOptions.forEach(item => { if(item.value == $event){ this.dataForm.outDeptName = item.name } })
      },
      inDeptChange($event) {
        this.deptOptions.forEach(item => { if(item.value == $event){ this.dataForm.inDeptName = item.name } })
      },
      // 打开商品列表弹窗
      openReceiveListDialog() {
        this.receiveListVisible = true
        this.$nextTick(() => {  this.$refs.receiveList.init() })
      },
      handleSelectionChange(val) {
        this.selectionList = val
      },
      //获取基地类型枚举
      getBasalTypeData(value) {
          let obj = {};
          obj = this.bizData.basalTypeData.find((item)=>{
              return item.value === value;
          });
          if(obj && obj.label){
              return obj.label;
          }
      },
      //  类型转换
      valueOrNameTypeChange(value) {
          let obj = {}
          obj = this.typeOptions.find(item => {
              if(item.value == value){
                  return item
              }
          })
          if(obj && obj.name){
              return obj.name
          }
      },
      tableRowClassName({row,rowIndex}){
        if (row.oldGoods) {
          return 'warning-row';
        }
        return '';
      },
      goodsChangeHandle(row){
        row.oldGoods = true
        this.oldGoods = row
        let params = {}
        params.ctgId = row.ctgId
        if(row.glassFlag == 'R'){
          params.ballGlass = this.optometryDetail.ballGlassOd
          params.postGlass = this.optometryDetail.postGlassOd
        }else if(row.glassFlag == 'L'){
          params.ballGlass = this.optometryDetail.ballGlassOs
          params.postGlass = this.optometryDetail.postGlassOs
        }
        let data = {
          params: params,
          oldGoods: row
        }

        this.goodsVisible = true
        this.$nextTick(() => {
          this.$refs.goodsDialog.init(data)
        })
      },
      getNewGood(data){
        // let oldGoods = data.oldGoods
        let goodsIndex
        let showIndex
        this.dataList.forEach((item,index) => {
          if(item.glassFlag == this.oldGoods.glassFlag && item.goodsId != this.oldGoods.goodsId){
            this.dataList.splice(index,1)
          }
        })
        this.dataList.forEach((item,index) => {
          if(item.glassFlag == this.oldGoods.glassFlag && item.goodsId == this.oldGoods.goodsId){
            showIndex = index*1+1
          }
        })
        this.dataList.splice(showIndex,0,data.newGoods)

        this.submitList.forEach((item,index) => {
          if(item.glassFlag == this.oldGoods.glassFlag){
            goodsIndex = index
          }
        })
        this.submitList.splice(goodsIndex,1,data.newGoods)

        this.submitList = [...this.submitList]
      },
      // 表单提交
      dataFormSubmit () {
				this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let sendDetailList = [];
            for(let i = 0; i < this.dataList.length; i++){
              for(let j = 0; j < this.submitList.length; j++){
                if(this.dataList[i].goodsId == this.submitList[j].goodsId){
                  this.submitList[j].outStockId = this.dataList[i].outStockId
                }
              }
            }
            this.submitList.forEach((item,index) => {
                sendDetailList.push({
                    id: item.id,
                    outStockId: item.outStockId,
                    goodsId: item.goodsId,
                    goodsQuantity: item.goodsQuantity
                })
            })
              let sendData ={};
              sendData.id = this.dataForm.id;
              sendData.workDeptId = this.dataForm.workDeptId;
              sendData.detailList = sendDetailList
            updateSendGlassSale(sendData).then(result => {
              this.$message.success('发料成功')
              this.visible = false
              this.$emit('refreshDataList')
							setTimeout(() => {
								this.ischeck = false
							},1000)
            }).catch(() => {
							this.ischeck = false
						})
          }else{
						this.ischeck = false
					}
        })
      },
        //获取出库列表
        getOutStockList(){
            getStockList().then(result => {
                let dataList = result.data.data
                let options = []
                dataList.forEach(item => {
                    options.push({value:item.id,name:item.name})
                })
                this.stockOptions = options
            })
        },
    //获取加工部门
     getDeptList(){
         let data = {
           deptTypes : [2,8]
         }
         getDeptInfoByDeptTypes(data).then(result => {
         let dataList = result.data.data
         let options = []
         dataList.forEach(item => {
           options.push({value:item.id,name:item.name})
         })
         this.deptOptions = options
       })
     }
    }
  }
</script>
<style>
  .el-table .warning-row {
      background: oldlace;
    }
</style>
<style lang="scss" scoped="scoped">

  .miui-table {
    width: 100%;
    margin: 10px 0;
    tr th {
      background-color: #f4f5f7;
    }
    tr th, tr td {
      padding: 10px 8px;
      border: solid 1px #e7e7e7;
      text-align: center;
      background-color: #fff;
    }
  }
</style>
